package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.dto.AddInventoryDTO;
import com.project.dto.AdjustInventoryDTO;
import com.project.dto.InventoryQueryDTO;
import com.project.entity.Inventory;
import com.project.mapper.InventoryMapper;
import com.project.result.PageResult;
import com.project.service.InventoryService;
import com.project.vo.InventoryDetailVO;
import com.project.vo.InventoryListVO;
import com.project.vo.InventoryStatisticsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService {
    @Autowired
    private InventoryMapper inventoryMapper;

    /**
     * 分页查询库存列表
     *
     * @return
     */
    @Override
    public PageResult<InventoryListVO> queryInventoryPage(InventoryQueryDTO queryDTO) {
        Page<InventoryListVO> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());
        Page<InventoryListVO> list = inventoryMapper.queryPage(page);
        PageResult<InventoryListVO> pageResult = new PageResult<>(list.getTotal(), list.getRecords());
        return pageResult;
    }

    /**
     * 根据材料ID获取库存信息
     *
     * @param materialId
     * @return
     */
    @Override
    public InventoryDetailVO getMaterialById(Integer materialId) {
        return inventoryMapper.queryMaterialDetailById(materialId);
    }

    /**
     * 根据库存ID获取库存信息
     *
     * @param inventoryId
     * @return
     */
    @Override
    public InventoryDetailVO getInventoryById(Integer inventoryId) {
        return inventoryMapper.queryInventoryById(inventoryId);
    }

    /**
     * 修改库存数量
     *
     * @param inventoryId
     */
    @Override
    public void updateInventoryById(Integer inventoryId, AdjustInventoryDTO inventoryDTO) {
        Inventory inventory = new Inventory();
        BeanUtils.copyProperties(inventoryDTO, inventory);
        inventory.setLastUpdate(LocalDateTime.now());
        inventoryMapper.updateById(inventoryId, inventory);
    }

    /**
     * 获取库存统计信息
     *
     * @param categoryId
     * @return
     */
    @Override
    public InventoryStatisticsVO getInventoryStatistics(Integer categoryId) {
        return inventoryMapper.getInventoryStatistics(categoryId);

    }

    /**
     * 添加库存
     *
     * @param addDTO
     * @return
     */
    @Override
    public boolean addInventory(AddInventoryDTO addDTO) {
        // 校验 materialId 是否存在（可选）
        // 判断材料ID是否存在
        if (addDTO.getMaterialId() == null) {
            throw new IllegalArgumentException("材料ID不能为空");
        }

        try {
            // 检查是否已存在该材料的库存记录
            LambdaQueryWrapper<Inventory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Inventory::getMaterialId, addDTO.getMaterialId());

            if (this.count(wrapper) > 0) {
    //            throw new IllegalStateException("该材料已有库存记录，不能重复新增");
                // 已存在：执行更新操作
                Inventory existingInventory = this.getOne(wrapper);
                UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("inventory_id", existingInventory.getInventoryId())
                        .set("qualified_qty", addDTO.getQualifiedQty())
                        .set("unqualified_qty", addDTO.getUnqualifiedQty())
                        .set("last_update", LocalDateTime.now());
                return this.update(updateWrapper);
            }else{
                // 新增操作
                Inventory inventory = new Inventory();
                BeanUtils.copyProperties(addDTO, inventory);
                inventory.setLastUpdate(LocalDateTime.now());
                return inventoryMapper.addInventory(inventory) > 0;
            }
        } catch (Exception e) {
            log.error("操作库存失败", e);
            throw new RuntimeException("操作库存失败: " + e.getMessage());
        }
    }

}